package com.bt.framework.manager

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES

/**
 * Created by hxm
 * Date: 2020/9/23
 * Description:Activity管理类
 */
object ActivityManager {

    //任务栈
    private val task = mutableListOf<Activity>()

    /**
     * 添加Activity
     */
    fun push(activity: Activity) {
        task.add(activity)
    }

    /**
     * 移除Activity
     */
    fun pop(activity: Activity) {
        task.remove(activity)
    }

    /**
     * 获取栈顶Activity
     */
    fun top(): Activity? {
        return task.lastOrNull()
    }

    /**
     * 关闭所有的Activity
     */
    fun finishAllActivity(callback: (() -> Unit)? = null) {
        val it = task.iterator()
        while (it.hasNext()) {
            val item = it.next()
            it.remove()
            item.finish()
        }
        callback?.invoke()
    }

    /**
     * 关闭其他Activity
     */
    fun finishOtherActivity(clazz: Class<out Activity>) {
        val it = task.iterator()
        while (it.hasNext()) {
            val item = it.next()
            if (item::javaClass != clazz) {
                it.remove()
                item.finish()
            }
        }
    }

    /**
     * 关闭指定Activity
     */
    fun finishActivity(clazz: Class<out Activity>) {
        val it = task.iterator()
        while (it.hasNext()) {
            val item = it.next()
            if (item::javaClass == clazz) {
                it.remove()
                item.finish()
            }
        }
    }

    /**
     * 判断指定Activity是否存在
     */
    fun isActivityExistsInStack(clazz: Class<out Activity>?): Boolean {
        if (clazz != null) {
            for (activity in task) {
                if (activity::javaClass == clazz) {
                    return true
                }
            }
        }
        return false
    }

    /**
     * 判断Activity是否销毁
     */
    @SuppressLint("ObsoleteSdkInt")
    fun isActivityDestroyed(context: Context): Boolean {
        val activity = findActivity(context)
        return if (activity != null) {
            if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) {
                activity.isDestroyed || activity.isFinishing
            } else activity.isFinishing
        } else true
    }

    /**
     * 获取当前Activity
     */
    private fun findActivity(context: Context): Activity? {
        if (context is Activity) {
            return context
        } else if (context is ContextWrapper) {
            return findActivity(context.baseContext)
        }
        return null
    }
}